package gamesolitaire;

import java.awt.*;
import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Solitaire {
	
private Canvas canvas;
private Board gBoard;
private Frame frame;
	
	/**constructor*/
	public Solitaire (){
	
	}
	/**initializes the content to create a game*/ 
	public void init () {
		this.loadContent();
		this.gBoard = new Board();
		this.gBoard.setLevel(Level.getLevel());
		
		// create the canvas
		this.canvas = new Canvas();
		this.canvas.setGboard(this.gBoard);
		//add mouse listener to canvas
		this.canvas.addMouseListener(new MouseClickHandeler());
		// init frame
		this.frame = new Frame(gBoard, canvas);
		//add canvas to frame
		Container pane = this.frame.getContentPane();
		pane.add(this.canvas);
		//set visible
		this.frame.setVisible(true);
	}
	/** event e logic*/
	public void update (MouseEvent e){
		// Retrieve row and column based on mouse position
		int row = e.getPoint().y / Peg.height;
		int col = e.getPoint().x /Peg.width;
		//put borders so we cannot click out of the Board
		if (row>= this.gBoard.getRowLength() || col>this.gBoard.getColLength()){
			return;
		}
		//Get value of selected Peg
		int val = this.gBoard.getCellValue(row, col);
		// decide what to do on Peg val
		switch(val){
			default:
					this.draw();
					break;
			case 0:
					if(this.gBoard.isSelected()){
						this.gBoard.moveSelectedPieceTo(row, col);
					}
					this.draw();
					break;
			case 1:
					this.gBoard.select(row, col);
					this.draw();
					break;
			case 2:
					this.gBoard.undoSelect();
					this.draw();
					break;
			
		}
	}
	/** trigger draw()*/
	public void draw(){
		this.canvas.repaint();
	}
	/** inner class reacts on mousclicks*/
	class MouseClickHandeler extends MouseAdapter{
		public void mouseReleased(MouseEvent e){
			update(e) ;
		}
	}
	/**Loads Pictures needed for the game + exception catcher*/
    public void loadContent() {
            try
            {
                    Peg.setPegPic(Filemanager.loadImage("./resources/pictures/GoldenBom.png"));
                    Peg.setSelectedPegPic(Filemanager.loadImage("./resources/pictures/SilverBom.png"));
                    Peg.setEmptyPic(Filemanager.loadImage("./resources/pictures/rageface.gif"));
                    Peg.setStaticPic(Filemanager.loadImage("./resources/pictures/Caut.png"));
            }
            catch (Exception e)
            {
                    System.out.println(e.getMessage());
            }
    }

}
